package com.utils;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class UpdateUtil {





	public static boolean isAllowedVersionCode(Context context){
		int versionCode = getVersionCode(context);
		System.out.println("本软件的版本是：" + versionCode);
		int minVersionCode=ParseXmlUtil.parseXml().getMinversion();
		if (versionCode>=minVersionCode)
		{
			return true;
		}
		else {
			return false;
		}

	}

	public static int getVersionCode(Context context) {
		int versionCode = 0;
		try {
			versionCode = context.getPackageManager().getPackageInfo(
					"com.app.hengyuan.fenqimall.agent.activity", 0).versionCode;
		} catch (PackageManager.NameNotFoundException e) {
			e.printStackTrace();
		}
		return versionCode;
	}

	public static String getVersionName(Context context) {
		String versionName = "1.X";
		try {
			return context.getPackageManager().getPackageInfo(
					"com.app.hengyuan.fenqimall.agent.activity", 0).versionName;
		} catch (PackageManager.NameNotFoundException e) {
			e.printStackTrace();
		}
		return versionName;
	}

	public static void showUpdateDialog(Context context,String title) {
		new AlertDialog.Builder(context)
				.setTitle("当前版本过低，请跟新版本!")
				.setPositiveButton("更新",
						new OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								downloadApk(context);
							}
						})
				.setNegativeButton("取消", null)
				.create()
				.show();
	}



	private static   void downloadApk(Context context) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					if (Environment.getExternalStorageState().equals(
							Environment.MEDIA_MOUNTED)) {
						String sdpath = Environment.getExternalStorageDirectory()
								+ "/";
						String mSavePath = sdpath + "download";
						URL url = new URL(ParseXmlUtil.parseXml().getUrl());
						HttpURLConnection conn = (HttpURLConnection) url
								.openConnection();
						conn.connect();
						int length = conn.getContentLength();
						InputStream is = conn.getInputStream();
						File file = new File(mSavePath);
						if (!file.exists()) {
							file.mkdir();
						}
						File apkFile = new File(mSavePath, ParseXmlUtil.parseXml().getName());
						FileOutputStream outputStream = new FileOutputStream(apkFile);
						int count = 0;
						byte buf[] = new byte[1024];
						int numread=0;
						do {
							numread = is.read(buf);
							count += numread;
							outputStream.write(buf, 0, numread);
						}while (numread>0);
						outputStream.close();
						is.close();
						installApk(context,apkFile);
					}
				} catch (MalformedURLException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}catch(Exception e)
				{
					e.printStackTrace();
				}
			}
		}).start();
	}

	/**
	 * 安装APK文件
	 */
	private  static void installApk(Context context,File file) {
		System.out.println(1);
		System.out.println(2);
		if (!file.exists()) {
			System.out.println(0);
			return;
		}
		Intent i = new Intent(Intent.ACTION_VIEW);
		System.out.println(3);
		i.setDataAndType(Uri.parse("file://" + file.toString()),
				"application/vnd.android.package-archive");
		context.startActivity(i);
	}
}
